var SrtParser = function() {			
};
SrtParser.prototype = {
	/**
	 * Creates an array containing a {id, start, end, text} object for each subtitle line. 
	 */
	parse: function(string) {
		var tim = new Date().getTime(); 
		var result = [];  
		var lines = string.split('\n');
		var errors = [];
		var s;
		var sid;  
		$(lines).each(function(i,l) {
			
			var _is_e = function(_l) { 
				if (!_l) {
					return true;
				}
				if (_l) {
					if (_l.length === 0) {return true} 
					if (_l === '\s') {return true}
					if (_l === '\r') {return true}
					if (_l === '\n') {return true}
					if (_l === '\r\n') {return true}
					if (_l.toString().trim().length == 0) {return true}
				} 
			};
			var is_e = _is_e(l);

		 
			// detect first line
			var is_f = !is_e && !isNaN(l) && ( (i===0) || _is_e(lines[i-1]) ) ;
						
			// detect last line			  
			var is_l = is_e && ( i>=lines.length-1 || !isNaN(lines[i+1]) ); 
			//--------------------------------------------------------------
			// id line
			//--------------------------------------------------------------
			if ( is_f ) {
				s = {id: parseInt(l), text:''};
				sid = i; 
				//console.log('first line: '+l)
			}
			
			//--------------------------------------------------------------
			// timecode line
			//--------------------------------------------------------------
		 
			if (i === sid+1) {
				if (l.indexOf(' --> ') !== -1) {
					s.start = l.split(' --> ')[0];
					s.end = l.split(' --> ')[1];					
				}
				else {
					errors.push( "Illegal timecode line at "+i+": "+l );
				}
				//console.log('tc line: '+l)
			} 

			//--------------------------------------------------------------
			// text lines
			//--------------------------------------------------------------
			if (i >= sid+2 && !is_l) {
				s.text += l.replace(/\r\n/g, '\n');
				if (!_is_e(lines[i+1])) {
					s.text += '\n';
				}
				//console.log('text line: '+l)
			}
			
			//--------------------------------------------------------------
			// last line
			//--------------------------------------------------------------
			if ( is_l ) { 
				result.push(s);
				//console.log('last line: '+l)
			}
			
		}); 
		if (errors.length > 0) {
			alert('errors happened!');
		}  
		
		return result;
	},
	/**
	 * Creates a string in srt format based on an array containing {id, start, end, text} objects 
	 */
	generate: function(array) {
		var result = ''
		$(array).each(function(i,l){
			result += l.id+'\n'
					 + l.start + ' --> '+ l.end+'\n'
					 + l.text +'\n\n';
		});
		return result;
	}
};